import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

service.interceptors.request.use((config) => {
  if (store.getters.token) {
    const logintime = localStorage.getItem('logintime')
    const timeout = 6000000
    const now = Date.now()
    if (now - logintime > timeout) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token失效!请重新登录'))
    } else {
      localStorage.setItem('logintime', now)
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
})

service.interceptors.response.use(res => {
  const { success, data, message } = res.data
  if (success) {
    // 如果成功则返回数据
    return data
  } else {
    // 如果数据失败,就用elementui的提示进行提示
    Message.error(message)
    // 并且return返回一个promise的reject 进行new一个error的错误提示
    return Promise.reject(new Error(message))
  }
},
err => {
  console.log(39, err.response)
  // 如果网络失败
  // return返回一个promise的reject 进行new一个error的错误提示err.message
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error(err.response.data.message)
  } else {
    Message.error(err.message)
  }

  return Promise.reject(new Error(err.message))
})

export default service
